package impl

import (
	"context"
	"github.com/samber/lo"
	"github.com/sirupsen/logrus"
	"html/template"
	"monoblog/common"
	"monoblog/common/register"
	"monoblog/domain/dao"
	"monoblog/domain/model"
	"monoblog/domain/service"
)

func init() {
	register.RegisterInstance[service.MomentService]("MomentService", func() service.MomentService {
		return &MomentServiceImpl{
			momentRepository: dao.NewMomentRepository(),
		} // 返回唯一实例
	})
}

type MomentServiceImpl struct {
	momentRepository *dao.MomentRepository
}

func (impl *MomentServiceImpl) UpdateReadById(ctx context.Context, id int64) error {
	err := impl.momentRepository.UpdateReadById(id, true)
	if err != nil {
		logrus.Errorf("[aid: %s] UpdateReadById failed, id: %d, err: %v", ctx.Value("aid"), id, err)
		return err
	}
	return nil
}

func (impl *MomentServiceImpl) UpdateReadByUserId(ctx context.Context, userId string) error {
	err := impl.momentRepository.UpdateReadByUserId(userId, true)
	if err != nil {
		logrus.Errorf("[aid: %s] UpdateReadByUserId failed, userId: %s, err: %v", ctx.Value("aid"), userId, err)
		return err
	}
	return nil
}

func (impl *MomentServiceImpl) FindListByUserId(ctx context.Context, userId string) ([]*model.Moment, error) {
	moments, _, err := impl.momentRepository.FindListByUserId(userId, common.BaseQuery{Page: 1, Size: 100})
	if err != nil {
		logrus.Errorf("[aid: %s] FindListByUserId failed, userId: %s, err: %v", ctx.Value("aid"), userId, err)
		return nil, err
	}

	lo.ForEach(moments, func(it *model.Moment, index int) {
		it.RenderedContent = template.HTML(it.Content)
	})
	return moments, nil
}
